
package com.epam.android.training.level1.db.poll;

import com.epam.android.training.level1.db.poll.Poll.Answer;
import com.epam.android.training.level1.db.poll.Poll.PollSuite;
import com.epam.android.training.level1.db.poll.Poll.Question;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Anton Novikau
 */
public class PollDbHelper extends SQLiteOpenHelper {

  private static final String TAG = PollDbHelper.class.getSimpleName();

  private static final String DB_NAME = "poll.db";

  private static final int DB_VERSION = 1;

  /**
   * Creates an instance of PollDbHelper.
   * 
   * @param context
   */
  public PollDbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    StringBuilder queryBuilder = new StringBuilder();

    // create poll table.
    queryBuilder.append("CREATE TABLE ").append(PollSuite.TABLE_NAME).append(" (")
        .append(PollSuite._ID).append(" INTEGER PRIMARY KEY,").append(PollSuite.DISPLAY_NAME)
        .append(" TEXT NOT NULL,").append(PollSuite.PASSED_PERCENT).append(" INTEGER DEFAULT -1);");
    db.execSQL(queryBuilder.toString());
    queryBuilder.setLength(0);

    // create questions table.
    queryBuilder.append("CREATE TABLE ").append(Question.TABLE_NAME).append(" (")
        .append(Question._ID).append(" INTEGER PRIMARY KEY,").append(Question.POLL_ID)
        .append(" INTEGER NOT NULL,").append(Question.DISPLAY_NAME).append(" TEXT NOT NULL,")
        .append("FOREIGN KEY(").append(Question.POLL_ID).append(") REFERENCES ")
        .append(PollSuite.TABLE_NAME).append("(").append(PollSuite._ID).append("));");

    db.execSQL(queryBuilder.toString());
    queryBuilder.setLength(0);
    // create answers table.
    queryBuilder.append("CREATE TABLE ").append(Answer.TABLE_NAME).append(" (").append(Answer._ID)
        .append(" INTEGER PRIMARY KEY,").append(Answer.QUESTION_ID).append(" INTEGER NOT NULL,")
        .append(Answer.DISPLAY_NAME).append(" TEXT NOT NULL,").append(Answer.IS_CORRECT)
        .append(" INTEGER DEFAULT 0,").append("FOREIGN KEY(").append(Answer.QUESTION_ID)
        .append(") REFERENCES ").append(Question.TABLE_NAME).append("(").append(Question._ID)
        .append("));");

    db.execSQL(queryBuilder.toString());
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
        + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + PollSuite.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + Question.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + Answer.TABLE_NAME);
    onCreate(db);
  }

}
